package com.hong.cloud.mall.practice.zuul.filter;

import com.hong.cloud.mall.practice.common.common.Constant;
import com.hong.cloud.mall.practice.user.model.pojo.User;
import com.hong.cloud.mall.practice.zuul.feign.UserFeignClient;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 描述：管理员鉴权过滤器
 */
@Component
public class AdminFilter extends ZuulFilter {
    @Autowired
    UserFeignClient userFeignClient;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE; // 前置过滤器
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {// 是否执行该过滤器，true代表需要过滤
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String requestURI = request.getRequestURI();
        // 如果是管理员登录，不需要用户认证，直接放行
        if (requestURI.contains("adminLogin")) {
            return false;
        }
        // 如果是管理员相关的请求，需要管理员认证，拦截，执行run方法
        return requestURI.contains("admin");
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx=RequestContext.getCurrentContext();
        HttpServletRequest request=ctx.getRequest();
        HttpSession session=request.getSession();
        User currentUser = (User)session.getAttribute(Constant.MALL_USER);
        // 校验是否登录
        if (currentUser==null){
            ctx.setSendZuulResponse(false);// 拦截该请求，不对其进行路由
            ctx.setResponseBody("{\"status\":10010,\"msg\":\"NEED_LOGIN\",\"data\":null}");
            ctx.getResponse().setContentType("application/json;charset=UTF-8");
            ctx.setResponseStatusCode(200);// 返回错误码
            return null;
        }
        // 校验是否是管理员
        Boolean adminRole = userFeignClient.checkAdminRole(currentUser);
        if (!adminRole) {
            ctx.setSendZuulResponse(false);// 拦截该请求，不对其进行路由
            ctx.setResponseBody("{\"status\":10011,\"msg\":\"NEED_ADMIN\",\"data\":null}");
            ctx.getResponse().setContentType("application/json;charset=UTF-8");
            ctx.setResponseStatusCode(200);// 返回错误码
        }
        return null;
    }
}
